package com.example.myapplication.utils

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.exifinterface.media.ExifInterface
import java.io.IOException
import java.io.OutputStream
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import kotlin.apply
import kotlin.collections.copyOf
import kotlin.collections.indices
import kotlin.collections.joinToString
import kotlin.collections.map
import kotlin.collections.toByteArray
import kotlin.let
import kotlin.ranges.downTo
import kotlin.ranges.step
import kotlin.text.chunked
import kotlin.text.isNullOrEmpty
import kotlin.text.toByteArray
import kotlin.text.toInt


/**
 */
object ImageUtils {

    /**
     *
     * @param context
     * @param bitmap
     * @param fileName
     * @return
     */
    fun saveImageToGallery(context: Context, bitmap: Bitmap, fileName: String): Boolean {
        val contentValues = ContentValues().apply {
            put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
            put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
                put(MediaStore.Images.Media.IS_PENDING, 1) // 标记为写入中
            } else {
                @Suppress("DEPRECATION")
                put(MediaStore.Images.Media.DATA, "${Environment.getExternalStorageDirectory()}/$fileName")
            }
        }

        val resolver = context.contentResolver
        var uri: Uri? = null
        var outputStream: OutputStream? = null

        try {
            uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
            uri ?: return false

            outputStream = resolver.openOutputStream(uri)
            outputStream ?: return false

            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)

            // Android 10+ 需要更新 IS_PENDING 状态
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                contentValues.clear()
                contentValues.put(MediaStore.Images.Media.IS_PENDING, 0)
                resolver.update(uri, contentValues, null, null)
            }

            // 通知系统相册刷新
            val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)
            context.sendBroadcast(mediaScanIntent)

            return true
        } catch (e: Exception) {
            uri?.let { resolver.delete(it, null, null) } // 失败时删除残留文件
            return false
        } finally {
            outputStream?.close()
        }
    }

    /**
     *
     * @param imagePath
     * @return
     */
    fun getCameraModel(imagePath: String?): String? {
        if (imagePath.isNullOrEmpty()) return null
        try {
            val exif = ExifInterface(imagePath)
            val model: String? = exif.getAttribute(ExifInterface.TAG_MODEL)
            return model ?: "未检测到镜头型号"
        } catch (e: IOException) {
            e.printStackTrace()
            return "读取EXIF信息失败！"
        }
    }

    private fun generateKey(keyStr: String): ByteArray {
        val digest = MessageDigest.getInstance("SHA-256")
        return digest.digest(keyStr.toByteArray(StandardCharsets.UTF_8)).copyOf(16)
    }

    private fun decryptText(encrypted: ByteArray, key: ByteArray): String? {
        try {
            val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
            cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"))
            return String(cipher.doFinal(encrypted), StandardCharsets.UTF_8)
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     *
     * @param imagePath
     * @param keyStr
     * @return
     */
    fun extractData(imagePath: String, keyStr: String): String? {
        val key = generateKey(keyStr)
        val bitmap = BitmapFactory.decodeFile(imagePath)!!
        val width = bitmap.width
        val height = bitmap.height
        val pixels = IntArray(width * height)
        bitmap.getPixels(pixels, 0, width, 0, 0, width, height)

        val lengthBits = StringBuilder()
        var bitIndex = 0
        outer@ for (i in pixels.indices) {
            val pixel = pixels[i]
            for (shift in 16 downTo 0 step 8) {
                if (lengthBits.length >= 32) break@outer
                lengthBits.append((pixel shr shift) and 1)
            }
        }
        val dataLength = lengthBits.toString().toInt(2)

        val binaryData = StringBuilder()
        bitIndex = 0
        outer@ for (i in pixels.indices) {
            val pixel = pixels[i]
            for (shift in 16 downTo 0 step 8) {
                if (bitIndex++ >= 32) { // 跳过长度头
                    if (binaryData.length < dataLength) {
                        binaryData.append((pixel shr shift) and 1)
                    } else {
                        break@outer
                    }
                }
            }
        }

        val hexStr = binaryData.chunked(8).map {
            it.toInt(2).toChar()
        }.joinToString("")

        val encrypted = hexStr.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
        return decryptText(encrypted, key)
    }
}